var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var multer = require('multer');
var http = require('http');
require('body-parser-xml')(bodyParser);
app.use(bodyParser.json({limit:'100mb'}));
app.use(bodyParser.urlencoded({ limit:'100mb', extended: true }));
//app.use(cookieParser());
app.use(function (req, res, next) {
  res.setTimeout(10 * 60 * 1000, function () {
    return res.status(408).send({
      errorMsg: '请求超时'
    })
  })
  next();
})
var DB = require('./SQLHelper')
//修改数据库配置
DB.config = {
  host: '111.111.11.11',
  port:3306,
  user:'hw',
  password: 'hw',
  database: 'hw'
}
//静态文件
app.use('/', express.static('./www'))
//执行数据库接口
app.post('/eval',async (req,res)=>{
  let sql = req.body.sql
  res.send(sql ? await DB.evalSync(sql) : { errorMsg:'请传入sql' })
})
//上传文件接口
app.post('/upload', multer({
  preservePath: true,
  storage: multer.diskStorage({
    destination: './uploads',
    filename: function (req, file, next) {
      var names = file.originalname.split('.')
      next(null, new Date().getTime() + '.' + names[names.length - 1])
    }
  })
}).single('file'), function (req, res) {
  res.send({
    url:'/file/' + req.file.filename,
    path:__dirname + '/' + req.file.path,
    mimetype:req.file.mimetype
  })
})
//访问文件接口
app.get('/file/:filename', function (req, res) {
  res.sendFile(__dirname + '/uploads/' + req.params.filename)
})
var httpServer = http.createServer(app)
//默认端口8080
httpServer.listen(8080, '0.0.0.0', function () {
  console.log('HTTP Server is running on: http://%s:%s', httpServer.address().address, httpServer.address().port);
})